package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.domain.Order;
import com.itheima.reggie.domain.OrderDetail;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;


    //用户下单
    @Override
    public void submit(Order order) {
        //1.获取登录用户id
        Long userId = UserHolder.get().getId();
        //2.获取收获地址对象
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收获地址异常，请重新选择下单");
        }
        //3.获取购物车对象
        List<Cart> cartList = cartService.list();
        if(CollUtil.isEmpty(cartList)){
            throw new CustomException("购物车为空，请选择菜品后下单");
        }
        //雪花id生成订单id
        Long orderId = IdWorker.getId();
        //订单支付总金额
        BigDecimal orderAmount = new BigDecimal("0");
        //4.填充订单明细
        for (Cart cart : cartList) {
            //4.1封装订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setImage(cart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            //4.2保存订单明细
            orderDetailMapper.insert(orderDetail);
            //4.3计算支付总金额 总金额=总金额+（单价*数量）
            orderAmount=orderAmount.add(orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber()+"")));
        }

        //5.保存订单
        order.setId(orderId);
        order.setNumber(orderId.toString());
        order.setStatus(1);
        order.setUserId(userId);
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(orderAmount);
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);
        //6.清空购物车
        cartService.clean();
    }
    //条件分页查询订单
    @Override
    public Page<Order> findOrderByPage(Integer pageNum, Integer pageSize, String number, LocalDateTime beginTime, LocalDateTime endTime) {
       //1.设置分页
        Page<Order> page = new Page<>(pageNum, pageSize);
        //2.设置查询条件
        //Select * from order where string number =? and time between beginTime and endTime;
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(number!=null,Order::getNumber,number);
        qw.between(beginTime!=null && endTime!=null,Order::getOrderTime,beginTime,endTime);
        //3.返回分页对象
       page= orderMapper.selectPage(page,qw);
        return page;
    }
    //查询历史订单
    @Override
    public Page<Order> findOrderByUserPage(Integer pageNum, Integer pageSize) {
        //1.设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Order::getOrderTime);
        //查询分页
        page = orderMapper.selectPage(page, qw);
        //2.遍历分页得到每一个order
        for (Order order : page.getRecords()) {
            Long orderId = order.getId();
            //根据orderid筛选出dish或setmeal集合 得到该订单下的所有菜品
            LambdaQueryWrapper<OrderDetail> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(qw1);
            //将集合封装到order对象的属性中
            order.setOrderDetails(orderDetailList);
        }
        //3.返回分页
        return page;
    }
}
